#include "rf_dongle.h"
#include "HAL.h"
#include "sys/byteorder.h"
#include "RingBuffer/lwrb.h"
#include "USB_task/USB_kbd.h"
#include "rf_dongle.h"
uint8_t rf_dongle_taskid = 0;
extern bool UsbSuspend_flag;
uint8_t rf_dongle_buffer[BUFFER_MAX_SIZE];
void get_data_deal(uint8_t *data, size_t len);
void state_changed(uint8_t state);

struct rf_port_cb get_cbs = {
    .get_data_cb = get_data_deal,
    .connect_state_changed = state_changed,
};

void get_data_deal(uint8_t *data, size_t len)
{
    OnBoard_SendMsg(USBTaskID, KEY_MESSAGE, 1, NULL);
    GPIOB_InverseBits(GPIO_Pin_14);
}

extern rf_data_t usb_leds;
void state_changed(uint8_t state)
{
    if (state == RF_DISCONNECTED) {
        PRINT("rf disconnected\n");
        usb_send_release();
    } else if (state == RF_CONNECTED) {
        PRINT("rf connected\n");
        if(!UsbSuspend_flag){
        rf_port_load_data_irq(RF_TYPE_REQ_KEY, (uint8_t *)&usb_leds, sizeof(usb_leds) - sizeof(usb_leds.data) + 1);
        LOG_INFO("set leds :%#x", usb_leds.data[0]);
        }
    }
}

uint16_t rf_dongle_event(uint8_t task_id, uint16_t events)
{
    if (events & SYS_EVENT_MSG) {
        tmos_event_hdr_t *pMsg;

        if ((pMsg = (tmos_event_hdr_t *)tmos_msg_receive(rf_dongle_taskid)) != NULL) {
            // Release the TMOS message
            tmos_msg_deallocate((uint8_t *)pMsg);
        }
        // return unprocessed events
        return (events ^ SYS_EVENT_MSG);
    }
    return 0;
}

void rf_dongle_init(void)
{
    rf_dongle_taskid = TMOS_ProcessEventRegister(rf_dongle_event);

    if(rf_trans_init()){
        PRINT("rf_trans_init error\n");
    }

    rf_port_init(rf_dongle_buffer, sizeof(rf_dongle_buffer), &get_cbs);
    rf_port_load_data_irq(RF_TYPE_REQ_KEY, NULL, 0);

#ifdef CONFIG_RF_PAIR
    rf_pair_task_init();
    rf_pair_start();
#endif
    rf_sync_init();
    rf_sync_start();
}


